package ks.app.smartDic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Locale;

import net.daum.mobilead.MobileAdView;


import com.google.android.apps.analytics.GoogleAnalyticsTracker;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.speech.tts.TextToSpeech;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TabHost;
import android.widget.Toast;

public class TabOriginal extends TabActivity {

	private static final int MY_DATA_CHECK_CODE = 4321;
	private static final int DIALOG_MP3 = 2;
	String query, sortOfDictionary;
	private TextToSpeech mTts;

	//AdView adView;
	MobileAdView adViewAdam;
	MultipleAd mAd;
	private static final int MODE_DEFINITION = 1;

	GoogleAnalyticsTracker tracker;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		final TabHost tb = getTabHost();

		LayoutInflater.from(this).inflate(R.layout.taboriginal,
				tb.getTabContentView(), true);

		Intent intent = getIntent();

		sortOfDictionary = intent
				.getStringExtra(getString(R.string.SORT_OF_DICTIONARY));
		query = intent.getStringExtra("query");

		NaverURLManager.setQuery(query);
		NaverURLManager.setSortOfDictionary(sortOfDictionary);

		tb.addTab(tb.newTabSpec("tab_test1").setIndicator("Definition")
				.setContent(R.id.view1));

		tb.addTab(tb.newTabSpec("tab_test2").setIndicator("Pronunciation")
				.setContent(R.id.view2));

		final WebView wv = (WebView) findViewById(R.id.web_holder);
		wv.getSettings().setJavaScriptEnabled(true);
		wv.setWebViewClient(new HelloWebViewClient()); // WebViewClient
		wv.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

		try {
			wv.loadUrl(NaverURLManager.getUrl(MODE_DEFINITION));
		} catch (Exception e) {
			ksLog.d(e.getMessage());
		}

		Button listenBtn = (Button) findViewById(R.id.btn_tts);

		listenBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				startTTSActivity();

			}
		});

		Button btnListenNAVER = (Button) findViewById(R.id.btn_ttsNAVER);
		btnListenNAVER.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {

				backgroundGetMP3 db = new backgroundGetMP3();
				db.execute();

			}
		});

		adViewAdam = (MobileAdView) findViewById(R.id.adviewAdam);
		mAd = new MultipleAd(getApplicationContext(), adViewAdam);
		mAd.displayAd();

		/*
		adView = new AdView(this, AdSize.BANNER,
				getString(R.string.ADMOB_PUBLISHER_ID));
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.layoutTabOriginal);

		RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM,
				RelativeLayout.TRUE);
		layout.addView(adView, layoutParams);
		adView.loadAd(new AdRequest());
		*/

		tracker = GoogleAnalyticsTracker.getInstance();
		tracker.start("UA-22873894-1", 20, this);
		tracker.trackPageView("/tabOriginal");
		tracker.dispatch();

	}

	void startTTSActivity() {

		mTts = new TextToSpeech(this, null);
		Intent checkIntent = new Intent();
		checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);

	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {

				play();
				mAd.displayAd();

			} else {

				Intent installIntent = new Intent();
				installIntent
						.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installIntent);

			}
		}
	}

	private void play() {

		mTts.setLanguage(Locale.US);
		mTts.speak(query, TextToSpeech.QUEUE_FLUSH, // Drop all pending entries
													// in the playback queue.
				null);
	}

	private class HelloWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {

			view.loadUrl(url);
			return true;

		}

	}

	protected void onResume() {

		super.onResume();

		mAd.displayAd();
	}

	private class backgroundGetMP3 extends AsyncTask<String, String, String> {

		MediaPlayer mp;
		AudioManager am;
		Downloader dn = new Downloader();
		FileInputStream inputStreamForPlay;

		httpClient hp;
		jerichoParser jp;
		InputStream http_data;

		private static final int STATUS_NONE = 0;
		private static final int STATUS_CACHED = 1;
		private static final int STATUS_GET_URL = 2;
		private static final int STATUS_NO_URL = 3;
		int playStatus = STATUS_NONE;
		private static final int MODE_DEFINITION = 1;
		int currentVolume;

		@Override
		protected String doInBackground(String... params) {

			mp = new MediaPlayer();
			am = (AudioManager) getSystemService(AUDIO_SERVICE);

			try {

				if (isExist(query)) {
					mp.setDataSource(inputStreamForPlay.getFD());
					playStatus = STATUS_CACHED;
				} else {
					hp = new httpClient();
					jp = new jerichoParser();
					http_data = hp
							.post(NaverURLManager.getUrl(MODE_DEFINITION));
					String url = jp.getMP3Url(http_data);

					if (url != null) {
						dn.DownloadFile(url, query + ".mp3");
						playStatus = STATUS_GET_URL;
					} else
						playStatus = STATUS_NO_URL;

					if (playStatus != STATUS_NO_URL)
						mp.setDataSource(url);
				}

				if (playStatus != STATUS_NO_URL) {
					mp.prepare();
					currentVolume = am
							.getStreamVolume(AudioManager.STREAM_MUSIC);
					am.setStreamVolume(AudioManager.STREAM_MUSIC, 100, 0);
				}

			} catch (Exception e) {

			}
			return null;
		}

		protected void onProgressUpdate(String... values) {

		}

		@Override
		protected void onPreExecute() {

			showDialog(DIALOG_MP3);

		}

		protected void onPostExecute(String result) {

			removeDialog(DIALOG_MP3);

			String message;

			if (playStatus != STATUS_NO_URL) {

				if (playStatus == STATUS_CACHED) {

					message = "내 폰에서 단어 PLAY";

				} else {

					message = "인터넷에서 단어 PLAY";
				}

				Toast.makeText(getApplicationContext(), message,
						Toast.LENGTH_LONG).show();
				mp.start();
				am.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);

			} else {

				Toast.makeText(getApplicationContext(), "단어를 재생 할 수 없습니다.",
						Toast.LENGTH_LONG).show();

			}

		}

		private Boolean isExist(String query) {

			File sdCard = Environment.getExternalStorageDirectory();
			File dir = new File(sdCard.getAbsolutePath() + "/smartDic/");
			dir.mkdirs();
			File file = new File(dir, query + ".mp3");

			if (file.exists()) {
				try {
					inputStreamForPlay = new FileInputStream(file);

					return true;
				} catch (Exception e) {
					return false;
				}

			}

			return false;

		}
	}

	public class Downloader {

		public void DownloadFile(String fileURL, String fileName) {
			try {

				File sdCard = Environment.getExternalStorageDirectory();
				File dir = new File(sdCard.getAbsolutePath() + "/smartDic/");
				dir.mkdirs();
				File file = new File(dir, fileName);

				URL u = new URL(fileURL);
				HttpURLConnection c = (HttpURLConnection) u.openConnection();
				c.setRequestMethod("GET");
				c.setDoOutput(true);
				c.connect();

				FileOutputStream f = new FileOutputStream(file);

				InputStream in = c.getInputStream();

				byte[] buffer = new byte[1024];
				int len1 = 0;
				while ((len1 = in.read(buffer)) > 0) {
					f.write(buffer, 0, len1);
				}
				f.close();
			} catch (Exception e) {
				ksLog.d("Downloader", e.getMessage());
			}

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_MP3: {
			ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage("단어 다운로드 중...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			return dialog;
		}
		}
		return null;
	}

}
